<template>
	<jk-table
		:cell-style="cellStyle"
		:highlight-hover-row="true"
		:highlight-current-row="true"
		:stripe="false"
		:span-method="mergeRowMethod"
		border
		:data="tableData"
	>
		<vxe-column title="工序" align="center" field="processName" fixed="left" :width="70"></vxe-column>
		<vxe-column title="人员明细" align="left" field="empName" fixed="left" :width="90">
			<!--<vxe-column title="人员明细" align="left" field="empName" :width="780">-->
			<!-- <template slot="header">
				<table-header :header="empHeader"></table-header>
			</template> -->
			<!-- <template slot-scope="scope">
				<table-body :header="empHeader" :data="scope.row.empList || []">
					<template slot="empMachineOutput" slot-scope="empScope">
						<jk-number-input v-model="empScope.row.empMachineOutput" size="mini"></jk-number-input>
					</template>
					<template slot="empMachineQty" slot-scope="empScope">
						<jk-number-input v-model="empScope.row.empMachineQty" size="mini"></jk-number-input>
					</template>
				</table-body>
			</template> -->
		</vxe-column>
		<vxe-column title="机台" align="left" field="machineName" :width="90"></vxe-column>
		<!-- <vxe-column title="单价" align="right" field="machineUnitPrice" :width="74"></vxe-column> -->
		<!-- <vxe-column title="品种明细" align="left" field="productList" :width="720">
			<template slot="header">
				<table-header :header="productHeader"></table-header>
			</template>
			<template slot-scope="scope">
				<table-body :header="productHeader" :data="scope.row.productList || []">
					<template slot="productMachineOutput" slot-scope="productScope">
						<jk-number-input v-model="productScope.row.productMachineOutput" size="mini" @change="productItemValChange($event, scope, productScope.rowIndex)"></jk-number-input>
					</template>
					<template slot="productMachineQty" slot-scope="productScope">
						<jk-number-input v-model="productScope.row.productMachineQty" size="mini" @change="productItemValChange($event, scope, productScope.rowIndex)"></jk-number-input>
					</template>
				</table-body>
			</template>
		</vxe-column> -->
		<!-- <vxe-column :title="`机台产量(${formData && formData.workshopCode && formData.workshopCode.toUpperCase() === 'QF' ? 'KM' : 'M'})`" align="right" field="machineOutput" :width="100"></vxe-column> -->
		<vxe-column title="单锭产量(kg)" align="right" field="spinOutputKg" :width="100"></vxe-column>
		<vxe-column title="总产量(kg)" align="right" field="machineQty" :width="100"></vxe-column>
		<vxe-column title="单锭产量(M)" align="right" field="spinOutputM" :width="100"></vxe-column>
		<vxe-column title="总产量(M)" align="right" field="machineOutput" :width="100"></vxe-column>
		<vxe-column title="机台工资" align="right" field="machineSalary" :width="100"></vxe-column>
		<vxe-column title="总工资" align="right" field="empMachineTotalSalary" :width="100"></vxe-column>
		<!-- <vxe-column :title="`工序产量(${formData && formData.workshopCode && formData.workshopCode.toUpperCase() === 'QF' ? 'KM' : 'M'})`" align="right" field="processOutput" :width="100"></vxe-column> -->
		<!-- <vxe-column title="工序产量(kg)" align="right" field="processQty" :width="100"></vxe-column> -->
	</jk-table>
</template>
<script>
    import { mathJsAdd, mathJsDiv, mathJsMul, mathJsSub } from '../../../../utils/jk/jk-cals';
    import mergeMixin from '../merge-mixin';
    import tableHeader from './table/header';
    import tableBody from './table/body';
    export default {
        mixins: [mergeMixin],
        components: {
            tableBody,
            tableHeader
        },
        props: {
            pageType: {
                type: String,
                default: ''
            },
            height: {
                type: Number,
                default: null
            },
            formData: {
                type: Object,
                default() {
                    return {};
                }
            },
            machineData: {
                type: Array,
                default() {
                    return [];
                }
            }
        },
        data() {
            return {
                productHeader: [
                    { title: '品种', key: 'productName', width: '200px', align: 'left' },
                    { title: '支数', key: 'yarnCount', width: '60px', align: 'right' },
                    { title: '单价', key: 'unitPrice', width: '90px', align: 'right' },
                    // { title: '品种原始产量', key: 'productMachineRawOutput', width: '100px', align: 'right' },
                    { title: '品种产量(M)', key: 'productMachineOutput', width: '130px', align: 'right', isSlot: true },
                    { title: '品种产量(kg)', key: 'productMachineQty', width: '120px', align: 'right', isSlot: true },
                    { title: '品种工资', key: 'productMachineSalary', width: '100%', align: 'right', isSlot: false }
                ],
                empHeader: [
                    { title: '人员', key: 'empName', width: '80px', align: 'left' },
                    { title: '人员机台产量(M)', key: 'empMachineOutput', width: '120px', align: 'right', isSlot: false },
                    // { title: '人员机台产量(kg)', key: 'empMachineQty', width: '120px', align: 'right', isSlot: false },
                    // { title: '人员工序产量(M)', key: 'empProcessOutput', width: '120px', align: 'right' },
                    // { title: '人员工序产量(kg)', key: 'empProcessQty', width: '120px', align: 'right' },
                    { title: '人员机台工资', key: 'empMachineSalary', width: '100px', align: 'right' }
                    // { title: '人员总工资', key: 'empTotalSalary', width: '100%', align: 'right' }
                ],
                bgColors: ['#19be6b', '#2d8cf0'],
                borderColors: ['#3fda8c', '#5cadff'],
                lineObj: {},
                tableData: []
            };
        },
        methods: {
            mergeRowMethod({ row, _rowIndex, column, visibleData }) {
                const fields = ['processName', 'empName', 'empMachineTotalSalary'];
                const cellValue = row[column.field];
                if (cellValue && fields.includes(column.field)) {
                    const prevRow = visibleData[_rowIndex - 1];
                    let nextRow = visibleData[_rowIndex + 1];
                    if (prevRow && prevRow[column.field] === cellValue) {
                        return { rowspan: 0, colspan: 0 };
                    } else {
                        let countRowspan = 1;
                        while (nextRow && nextRow[column.field] === cellValue) {
                            nextRow = visibleData[++countRowspan + _rowIndex];
                        }
                        if (countRowspan > 1) {
                            return { rowspan: countRowspan, colspan: 1 };
                        }
                    }
                }
            },
            productItemValChange(e, scope, productIndex) {
                // 细纱和并条的工资的计算逻辑不一样(在生产工序配置)，单独处理
                if (['XS', 'BT', 'TB', 'EB', 'MB'].includes(scope.row.processCode.toUpperCase())) {
                    /**
                     * 首先，计算当前机台的总产量(M,KG)
                     * */
                    let currentMachineTotalOutput = 0;
                    let currentMachineTotalQty = 0;
                    let currentMachineTotalSalary = 0;
                    this.tableData.forEach((machineItem) => {
                        machineItem.productList.forEach(productItem => {
                            if (machineItem.machineName === scope.row.machineName) {
                                currentMachineTotalOutput = mathJsAdd(currentMachineTotalOutput, productItem.productMachineOutput || 0);
                                currentMachineTotalQty = mathJsAdd(currentMachineTotalQty, productItem.productMachineQty || 0);
                            }
                        });
                    });
                    this.$set(this.tableData[scope.rowIndex], 'machineOutput', Number(currentMachineTotalOutput.toFixed(2)));
                    this.$set(this.tableData[scope.rowIndex], 'machineQty', Number(currentMachineTotalQty.toFixed(2)));
                    /**
                     * 接着，根据机台总产量(M),计算机台工资
                     * */
                    // 工序为细纱时
                    if (scope.row.processCode.toUpperCase() === 'XS') {
                        // 大于或等于基准产量(M)时，机台工资 = 固定工资
                        if (this.tableData[scope.rowIndex].machineOutput >= this.tableData[scope.rowIndex].referenceOutput) {
                            currentMachineTotalSalary = this.tableData[scope.rowIndex].regularSalary;
                            // 清空品种下的单价
                            this.tableData[scope.rowIndex].productList.forEach(productItem => {
                                this.$set(productItem, 'unitPrice', 0);
                            });
                        } else {
                            // 小于基准产量(M)时，机台工资 = 产量(M) * 单价（工序上的单价）
                            currentMachineTotalSalary = mathJsMul(this.tableData[scope.rowIndex].machineOutput || 0, this.tableData[scope.rowIndex].machineUnitPrice || 0);
                            currentMachineTotalSalary = Number(currentMachineTotalSalary.toFixed(2));
                            // 修正品种下的单价
                            this.tableData[scope.rowIndex].productList.forEach(productItem => {
                                this.$set(productItem, 'unitPrice', this.tableData[scope.rowIndex].machineUnitPrice);
                            });
                        }
                    } else {
                        // 为并条时
                        let gz = 0;
                        // 大于基准产量(M)时，工资 = 基准产量(M) * 左侧单价 + （产量(M) - 基准产量(M)）* 右侧单价;
                        const outputM = this.tableData[scope.rowIndex].machineOutput * 1000; // 因为前纺是输入的单位是KM，而工资又是按照M计算，所以需要换算为M
                        if (outputM >= this.tableData[scope.rowIndex].referenceOutput) {
                            gz = mathJsMul(this.tableData[scope.rowIndex].referenceOutput, this.tableData[scope.rowIndex].machineUnitPrice);
                            let diffGz = mathJsSub(outputM, this.tableData[scope.rowIndex].referenceOutput);
                            diffGz = mathJsMul(diffGz, this.tableData[scope.rowIndex].regularSalary);
                            gz = mathJsAdd(diffGz, gz);
                        } else {
                            // 产量小于基准产量时，工资 = 产量(M) * 左侧单价
                            gz = mathJsMul(outputM, this.tableData[scope.rowIndex].machineUnitPrice || 0);
                        }
                        gz = gz.toFixed(2);
                        gz = Number(gz);
                        // 修正品种下的单价
                        this.tableData[scope.rowIndex].productList.forEach(productItem => {
                            this.$set(productItem, 'unitPrice', 0);
                        });
                        currentMachineTotalSalary = gz;
                    }

                    this.$set(this.tableData[scope.rowIndex], 'machineSalary', currentMachineTotalSalary);
                    /**
                     * 接着，将机台的工资分别均分给下面的品种(工资)和人员(工资)
                     * */
                    // 品种工资 = 机台工资 / 品种数
                    this.tableData[scope.rowIndex].productList.forEach(productItem => {
                        let productItemSalary = 0;
                        if (this.tableData[scope.rowIndex].productList.length) {
                            productItemSalary = mathJsDiv(currentMachineTotalSalary, this.tableData[scope.rowIndex].productList.length);
                            productItemSalary = Number(productItemSalary.toFixed(2));
                        }
                        this.$set(productItem, 'productMachineSalary', productItemSalary);
                    });

                    // 机台下的人员(工资、产量) = 机台(工资、产量) / 人数
                    this.tableData[scope.rowIndex].empList.forEach(empItem => {
                        let empMachineSalary = 0;
                        let empMachineOutput = 0;
                        let empMachineQty = 0;
                        if (this.tableData[scope.rowIndex].empList.length) {
                            empMachineSalary = Number(mathJsDiv(currentMachineTotalSalary, this.tableData[scope.rowIndex].empList.length).toFixed(2));
                            empMachineOutput = Number(mathJsDiv(currentMachineTotalOutput, this.tableData[scope.rowIndex].empList.length).toFixed(2));
                            empMachineQty = Number(mathJsDiv(currentMachineTotalQty, this.tableData[scope.rowIndex].empList.length).toFixed(2));
                        }
                        this.$set(empItem, 'empMachineSalary', empMachineSalary);
                        this.$set(empItem, 'empMachineOutput', empMachineOutput);
                        this.$set(empItem, 'empMachineQty', empMachineQty);
                    });

                    /**
                     * 然后，计算当前机台所属工序的总产量
                     * */
                    this.calCurrentMachineOfProcessTotalQty(e, scope, productIndex);
                } else {
                    this.otherProcessCal(e, scope, productIndex);
                }
                this.updateData();
            },
            // 其他工序的计算方法
            otherProcessCal(e, scope, productIndex) {
                /**
                 * 首先，计算当前品种的工资
                 * */
                let productMachineSalary = 0;
                // 前纺-输入的是KM，但是工资根据M计算，所以需要乘以1000
                if (scope.row.processCode && ['SM', 'BT', 'TB', 'EB', 'MB', 'CS'].includes(scope.row.processCode.toUpperCase())) {
                    const outputM = mathJsMul(this.tableData[scope.rowIndex].productList[productIndex].productMachineOutput || 0, 1000);
                    productMachineSalary = mathJsMul(outputM, this.tableData[scope.rowIndex].productList[productIndex].unitPrice || 0).toFixed(2);
                } else {
                    // 并线根据公斤计算工资
                    if (scope.row.processCode && ['BX'].includes(scope.row.processCode.toUpperCase())) {
                        const outputKg = this.tableData[scope.rowIndex].productList[productIndex].productMachineQty || 0;
                        productMachineSalary = mathJsMul(outputKg, this.tableData[scope.rowIndex].productList[productIndex].unitPrice || 0).toFixed(2);
                    } else {
                        productMachineSalary = mathJsMul(this.tableData[scope.rowIndex].productList[productIndex].productMachineOutput || 0, this.tableData[scope.rowIndex].productList[productIndex].unitPrice || 0).toFixed(2);
                    }
                }
                productMachineSalary = Number(productMachineSalary);
                this.$set(this.tableData[scope.rowIndex].productList[productIndex], 'productMachineSalary', productMachineSalary);

                /**
                 * 接着，计算当前机台的总产量、总工资
                 * */
                let currentMachineTotalOutput = 0;
                let currentMachineTotalQty = 0;
                let currentMachineTotalSalary = 0;
                this.tableData.forEach((machineItem) => {
                    machineItem.productList.forEach(productItem => {
                        if (machineItem.machineName === scope.row.machineName) {
                            currentMachineTotalOutput = mathJsAdd(currentMachineTotalOutput, productItem.productMachineOutput || 0);
                            currentMachineTotalQty = mathJsAdd(currentMachineTotalQty, productItem.productMachineQty || 0);
                            currentMachineTotalSalary = mathJsAdd(currentMachineTotalSalary, productItem.productMachineSalary || 0);
                        }
                    });
                });
                this.$set(this.tableData[scope.rowIndex], 'machineOutput', Number(currentMachineTotalOutput.toFixed(2)));
                this.$set(this.tableData[scope.rowIndex], 'machineQty', Number(currentMachineTotalQty.toFixed(2)));
                this.$set(this.tableData[scope.rowIndex], 'machineSalary', Number(currentMachineTotalSalary.toFixed(2)));

                /**
                 * 然后，计算当前机台所属工序的总产量
                 * */
                this.calCurrentMachineOfProcessTotalQty(e, scope, productIndex);
                /**
                 * 再，将当前机台的总产量均分给机台下面的人员
                 * */
                if (this.tableData[scope.rowIndex].empList && this.tableData[scope.rowIndex].empList.length) {
                    let everyoneEmpOutput = 0;
                    let everyoneEmpQty = 0;
                    everyoneEmpOutput = mathJsDiv(currentMachineTotalOutput, this.tableData[scope.rowIndex].empList.length).toFixed(1);
                    everyoneEmpOutput = Number(everyoneEmpOutput);

                    everyoneEmpQty = mathJsDiv(currentMachineTotalQty, this.tableData[scope.rowIndex].empList.length).toFixed(1);
                    everyoneEmpQty = Number(everyoneEmpQty);
                    this.tableData.forEach((machineItem) => {
                        if (machineItem.machineName === scope.row.machineName) {
                            machineItem.empList.forEach(empItem => {
                                this.$set(empItem, 'empMachineOutput', Number(everyoneEmpOutput.toFixed(2)));
                                this.$set(empItem, 'empMachineQty', Number(everyoneEmpQty.toFixed(2)));
                                let empMachineSalary = mathJsMul(currentMachineTotalSalary, machineItem.empList.length).toFixed(2);
                                empMachineSalary = Number(empMachineSalary);
                                this.$set(empItem, 'empMachineSalary', machineItem.empList && machineItem.empList.length ? empMachineSalary : 0);
                            });
                        }
                    });
                }
                /**
                 * 最后，计算当前机台下人员的工序产量和总工资
                 * */
                this.calCurrentMachineEmpProcessQtyAndSalary(e, scope, productIndex);
            },
            calCurrentMachineOfProcessTotalQty(e, scope, productIndex) {
                /**
                 * 然后，计算当前机台所属工序的总产量
                 * */
                let currentProcessTotalOutput = 0;
                let currentProcessTotalQty = 0;
                this.tableData.forEach((machineItem) => {
                    if (machineItem.processName === scope.row.processName) {
                        currentProcessTotalOutput = mathJsAdd(currentProcessTotalOutput, machineItem.machineOutput || 0);
                        currentProcessTotalQty = mathJsAdd(currentProcessTotalQty, machineItem.machineQty || 0);
                    }
                });
                this.tableData.forEach((machineItem) => {
                    if (machineItem.processName === scope.row.processName) {
                        this.$set(machineItem, 'processOutput', Number(currentProcessTotalOutput.toFixed(2)));
                        this.$set(machineItem, 'processQty', Number(currentProcessTotalQty.toFixed(2)));
                    }
                });
            },
            /**
             * 最后，计算当前机台下人员的工序产量和总工资
             * */
            calCurrentMachineEmpProcessQtyAndSalary(e, scope, productIndex) {
                const empConfig = {};
                const empList = this.tableData[scope.rowIndex].empList ? JSON.parse(JSON.stringify(this.tableData[scope.rowIndex].empList)) : [];
                // 将当前机台的看台人员保存起来,后续只计算这些人的产量和工资
                empList.forEach(x => {
                    if (!empConfig[x.empName]) {
                        empConfig[x.empName] = {
                            empProcessOutput: 0,
                            empProcessQty: 0,
                            empTotalSalary: 0
                        };
                    }
                });
                // 将每个人的机台产量、工资分别累加起来
                this.tableData.forEach((machineItem) => {
                    machineItem.empList.forEach(empItem => {
                        if (empConfig[empItem.empName]) {
                            empConfig[empItem.empName].empProcessOutput = mathJsAdd(empConfig[empItem.empName].empProcessOutput, empItem.empMachineOutput || 0);
                            empConfig[empItem.empName].empProcessQty = mathJsAdd(empConfig[empItem.empName].empProcessQty, empItem.empMachineQty || 0);
                            empConfig[empItem.empName].empTotalSalary = mathJsAdd(empConfig[empItem.empName].empTotalSalary, empItem.empMachineSalary || 0);
                        }
                    });
                });
                // 赋值
                this.tableData.forEach((machineItem) => {
                    machineItem.empList.forEach(empItem => {
                        if (empConfig[empItem.empName]) {
                            this.$set(empItem, 'empProcessOutput', Number(empConfig[empItem.empName].empProcessOutput.toFixed(2)));
                            this.$set(empItem, 'empProcessQty', Number(empConfig[empItem.empName].empProcessQty.toFixed(2)));
                            this.$set(empItem, 'empTotalSalary', Number(empConfig[empItem.empName].empTotalSalary.toFixed(2)));
                        }
                    });
                });
            },
            updateData() {
                this.$emit('on-update', JSON.parse(JSON.stringify(this.tableData)));
            }
        },
        watch: {
            machineData: {
                handler(newVal) {
                    this.tableData = newVal && newVal.length ? JSON.parse(JSON.stringify(newVal)) : [];
                },
                deep: true,
                immediate: true
            },
            formData: {
                handler(newVal) {
                    // 前纺，产量的单位为:KM
                    if (newVal && newVal.workshopCode && newVal.workshopCode.toUpperCase() === 'QF') {
                        this.productHeader.forEach(x => {
                            if (x.key === 'productMachineOutput') this.$set(x, 'title', '品种产量(KM)');
                        });
                        this.empHeader.forEach(x => {
                            if (x.key === 'empMachineOutput') this.$set(x, 'title', '人员机台产量(KM)');
                            if (x.key === 'empProcessOutput') this.$set(x, 'title', '人员工序产量(KM)');
                        });
                    } else {
                        // 后纺，产量的单位为:M
                        this.productHeader.forEach(x => {
                            if (x.key === 'productMachineOutput') this.$set(x, 'title', '品种产量(M)');
                        });
                        this.empHeader.forEach(x => {
                            if (x.key === 'empMachineOutput') this.$set(x, 'title', '人员机台产量(M)');
                            if (x.key === 'empProcessOutput') this.$set(x, 'title', '人员工序产量(M)');
                        });
                    }
                },
                deep: true,
                immediate: true
            }
        }
    };
</script>
<style scoped lang="scss">
</style>
